package com.chagee.store.operation.server.task;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.chagee.store.operation.api.response.SearchSupplierResponse;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.config.XxlJobConfig;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.service.StoreConfigurationBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.service.GenerateWorkOrderAndTaskExecutionTableData;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.biz.SupplierDetailBizService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName CreateWorkOrderJobHandler  //类名称
 * @Description: 类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/4/8 15:03	//创建时间
 * @UpdateUser: Jacky-zhan
 * @UpdateDate: 2024/4/8 15:03	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Component
public class CreateWorkOrderJobHandler {

	@Resource
	private StoreBaseService storeBaseService;
	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;
	@Resource
	private GenerateWorkOrderAndTaskExecutionTableData generateWorkOrderData;
	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private SupplierDetailBizService supplierDetailBizService;

	private final SimpleDateFormat format = new SimpleDateFormat(CommonConstant.FORMAT);

	@XxlJob("generateCreateWorkOrder")
	public ReturnT<String> generateCreateWorkOrder(String param) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
		//每天的21:00/22:00/23:00/00:00去查询门店的信息，去查看已开启打烊配置的门店，然后再验证创建工单的时间，
		Date date = new Date();
		if (StringUtils.isNotBlank(param)) {
			log.info("generateCreateWorkOrder_param: {}", param);
			Map map = Optional.ofNullable(JSONUtil.toBean(param, Map.class)).orElse(new HashMap(16));
			String date1 = String.valueOf(map.get("date"));
			try {
				date = format.parse(date1);
			} catch (Exception e) {
				log.error("generateCreateWorkOrder_param: {} ", param, e);
				return ReturnT.FAIL;
			}
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		log.info("在{}的时候,查询开启三方打烊功能的门店,", date);

		List<SearchSupplierResponse> supplierList = supplierDetailBizService.supplierList();
		Map<String, String> supplierMap = supplierList.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).collect(Collectors.toMap(SearchSupplierResponse::getCode, SearchSupplierResponse::getName, (a, b) -> b));


		long startIndex = 0L;
		while (true) {
			List<StoreDO> storeDOList = storeBaseService.selectByClosingTaskStatus(startIndex);

			if (CollectionUtils.isEmpty(storeDOList)) {
				break;
			}
			List<String> storeNoList = storeDOList.stream().map(StoreDO::getStoreNo).distinct().collect(Collectors.toList());
			//查询当前时间段工单
			String dateTime = simpleDateFormat.format(date);
			String startDate = dateTime.concat(":00:00");
			String endDate = dateTime.concat(":59:59");
			List<WorkOrderDO> workOrderDOList = workOrderBaseService.selectListByDate(startDate, endDate, storeNoList);
			log.info("在{}段的时候,查询已生成工单的门店:{}", startDate, JSONObject.toJSONString(workOrderDOList.stream().map(WorkOrderDO::getStoreCode).collect(Collectors.toList())));
			Map<String, WorkOrderDO> orderDOMap = workOrderDOList.stream().collect(Collectors.toMap(WorkOrderDO::getStoreCode, Function.identity(), (a, b) -> a));

			List<StoreConfigurationDO> storeConfigurationDOList = storeConfigurationBaseService.batchGetByStoreCodeList(storeNoList);
			Map<String, StoreConfigurationDO> configurationDOMap = storeConfigurationDOList.stream().collect(Collectors.toMap(StoreConfigurationDO::getStoreCode, Function.identity(), (a, b) -> a));

			for (StoreDO storeDO : storeDOList) {
				String storeNo = storeDO.getStoreNo();
				StoreConfigurationDO configurationDO = configurationDOMap.get(storeNo);
				if (Objects.nonNull(configurationDO)) {
					if (StringUtils.isNotBlank(configurationDO.getClosingWorkOrderCreateTime())) {
						String closingWorkOrderCreateTime = configurationDO.getClosingWorkOrderCreateTime();
						String split = closingWorkOrderCreateTime.split("\\.")[0];
						//如果创建工单的时间小时在date的小时上
						if (String.valueOf(hour).equals(split)) {
							WorkOrderDO workOrderDO = orderDOMap.get(storeDO.getStoreNo());
							if (Objects.nonNull(workOrderDO)) {
								continue;
							}
							String supplierName = StringUtils.EMPTY;
							if (MapUtil.isNotEmpty(supplierMap) && StringUtils.isNotBlank(supplierMap.get(configurationDO.getSupplierNo()))) {
								supplierName = supplierMap.get(configurationDO.getSupplierNo());
							}

							log.info("开始对于门店{}创建工单.", storeDO.getStoreNo());
							Boolean b = false;
							try {
								b = generateWorkOrderData.generateData(storeDO.getStoreNo(), supplierName);
							} catch (Exception e) {
								log.error("门店{},创建工单失败:", storeDO.getStoreNo(), e);
							}
							log.info("门店{},创建工单结果: {}", storeDO.getStoreNo(), b);
						}
					}
				}
			}
			startIndex = Math.toIntExact(storeDOList.stream().map(StoreDO::getId).max(Comparator.naturalOrder()).orElse(0L));
		}
		return ReturnT.SUCCESS;
	}

}
